package com.distributor;

import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AddBalance extends Activity implements OnClickListener {
	Double amount;
	EditText etAmount, etTransactionPin;
	Button btnOk, btnOkConfirmation, btnCancelConfirmation;
	TextView tvConfirmationText;
	MD5Generator md5Generator = new MD5Generator();
	ResellerInfo agentInfo = AppData.agentInfo;
	ProgressDialog pd = null;
	HttpClient httpclient;
	HttpPost httppost = new HttpPost(AppData.hostURL
			+ "/WebService/iTopUp/distributorapp.php");
	Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_balance);

		etAmount = (EditText) findViewById(R.id.etAmount);
		etAmount.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);

		etTransactionPin = (EditText) findViewById(R.id.etTransactionPin);

		btnOk = (Button) findViewById(R.id.btn_ok);
		// btnCancel=(Button)findViewById(R.id.btn_Cancel);
		btnOk.setOnClickListener(this);
		// btnCancel.setOnClickListener(this);
	}

	public void onClick(View v) {

		if (v == btnOk) {
			try {
				if (etAmount.getText().toString().trim().length() > 0) {
					if (AppData
							.getUserInfo()
							.getTransactionPassword()
							.equals(md5Generator.MD5(etTransactionPin.getText()
									.toString()))) {
						// dismiss();
						new confirmation_layout(AddBalance.this).show();

						

						
						// show();
					} else {
						Toast.makeText(this, "Invalid Transaction PIn",
								Toast.LENGTH_SHORT).show();
						etTransactionPin.setText("");
					}

				} else {
					Toast.makeText(AddBalance.this, "Please Enter Amount.",
							Toast.LENGTH_SHORT).show();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// else if(v==btnCancel)
		// {
		// //dismiss();
		// finish();
		// }

		

	}

	

	public class confirmation_layout extends Dialog implements android.view.View.OnClickListener {
		Context ctx;

		public confirmation_layout(Context context) 
		{
			super(context);
			
			ctx=context;
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.confirmation_layout);

			tvConfirmationText = (TextView) findViewById(R.id.tvConfirmationText);

			btnOkConfirmation = (Button) findViewById(R.id.btn_Ok_confirmation);
			btnCancelConfirmation = (Button) findViewById(R.id.btn_Continue_confirmation);

			tvConfirmationText.setText("Tuma "
					+ etAmount.getText().toString()
					+ " Tshs kwenda namba " + agentInfo.getPhone1()
					+ ".");
			btnOkConfirmation.setOnClickListener(this);
			btnCancelConfirmation.setOnClickListener(this);
			

		}

		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == btnOkConfirmation) {
				
				amount = Double.parseDouble(etAmount.getText().toString()) * 100;
				new Thread(addBalance, "Add Balance").start();
				pd = ProgressDialog.show(AddBalance.this, "please wait.", null);
				pd.setContentView(R.layout.progress);
				 dismiss();
			} else if (v == btnCancelConfirmation) {
				dismiss();
				
			}
		}

	}
	
	double roundTwoDecimals(double d) {
		DecimalFormat twoDForm = new DecimalFormat("#.##");
		return Double.valueOf(twoDForm.format(d));
	}

	Runnable addBalance = new Runnable() {

		public void run() {
			try {
				httpclient = new DefaultHttpClient();
				String checksumString = AppData.getUserInfo().getLoginID()
						+ "|" + agentInfo.getPhone1() + "|" + amount + "|"
						+ AppData.getUserInfo().getpublickey();
				System.out.println("Check sum string===>" + checksumString);
				String finalChecksum = md5Generator.MD5(md5Generator
						.SHA1(checksumString));
				System.out.println("Final Checksum:" + finalChecksum);
				try {

					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("function",
							"BalanceTransfer"));
					nameValuePairs.add(new BasicNameValuePair("LoginId",
							AppData.getUserInfo().getLoginID()));
					nameValuePairs.add(new BasicNameValuePair("Phone1",
							agentInfo.getPhone1()));
					nameValuePairs.add(new BasicNameValuePair("Amount", Double
							.toString(amount)));
					nameValuePairs.add(new BasicNameValuePair("Checksum",
							finalChecksum));

					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

					ResponseHandler<String> responseHandler = new BasicResponseHandler();

					String response = httpclient.execute(httppost,
							responseHandler);
					System.out.println("Response:" + response);

					final JSONObject jsonObject = new JSONObject(response);

					if (jsonObject.getString("ResponseCode").equals("000")) {

						handler.post(new Runnable() {

							public void run() {
								// TODO Auto-generated method stub
								// try {
								// tvBalance.setText(""+roundTwoDecimals(Double.parseDouble(jsonObject.getString("Balance"))/100));
								// } catch (JSONException e) {
								// // TODO Auto-generated catch block
								// e.printStackTrace();
								// }
								pd.dismiss();
								Toast.makeText(AddBalance.this,
										"Balance Transfered Successfully",
										Toast.LENGTH_LONG).show();

							}
						});

					} else {
						handler.post(new Runnable() {

							public void run() {
								// TODO Auto-generated method stub
								pd.dismiss();
								try {
									Toast.makeText(
											AddBalance.this,
											jsonObject
													.getString("ResponseDescription"),
											Toast.LENGTH_SHORT).show();

								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
						});

					}
				} catch (final JSONException e) {
					handler.post(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							pd.dismiss();
							Toast.makeText(AddBalance.this, e.getMessage(),
									Toast.LENGTH_LONG).show();
						}
					});
				} catch (UnknownHostException e) {

					handler.post(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							pd.dismiss();
							Toast.makeText(AddBalance.this,
									getString(R.string.conn_msg),
									Toast.LENGTH_LONG).show();
						}
					});

				} catch (final ClientProtocolException e) {
					// TODO Auto-generated catch block
					handler.post(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							pd.dismiss();
							Toast.makeText(AddBalance.this,
									getString(R.string.conn_msg),
									Toast.LENGTH_LONG).show();
						}
					});

				}

				catch (final IOException e) {
					handler.post(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							pd.dismiss();
							Toast.makeText(AddBalance.this, e.getMessage(),
									Toast.LENGTH_LONG).show();
						}
					});
				}
			}

			catch (Exception e) {
				e.printStackTrace();
			}

		}
	};
}
